<template>
   <!-- 文件上传 -->
  <!-- <input 
      type="file" 
      @change="handleFileChange" 
      accept=".docx,.xlsx,.pdf,.doc" 
      class="file-input"
    /> -->
  
    <!-- 状态提示 -->
    <div v-if="loading" class="status">文件加载中...</div>
    <div v-if="error" class="error">{{ error }}</div>
  <t-form
    ref="formRef"
    :data="assessInterviewDetail"
    :requiredMark="false"
    labelAlign="top"
    @submit="onSubmit"
  >
    <div
      class="upload-container"
      :class="isDetail ? 'upload-con2' : 'upload-con1'"
    >
      <!-- 左侧菜单 -->
      <t-menu
        class="upload-container__menu"
        theme="light"
        :expanded="expandedKeys"
        @expand="handleExpand"
        @change="handleMenuChange"
        v-model:value="defaultValue"
      >
        <t-submenu
          mode="popup"
          v-for="item in assessInterviewDetail"
          :key="item.id"
          :value="item.id"
        >
          <template #title>
            <span>{{ item.name }}</span>
          </template>
          <t-menu-item
            v-for="child in item?.child"
            :key="child.id"
            :value="child.code"
          >
            {{ child.name }}</t-menu-item
          >
        </t-submenu>
      </t-menu>
      <t-divider class="upload-container__line" layout="vertical" />
     <!-- 右侧内容 -->
      <div
        class="upload-container__up"
        ref="scrollContainer"
        @scroll.passive="handleScroll"
      >
        <div v-for="item in assessInterviewDetail" :key="item.code">
          <div class="title" :id="item.child[0].code">
            {{ item.name }}
          </div>
          <div
            v-for="child in item.child"
            :id="child.code"
            :key="child.code"
          >
            <div class="sub-title">{{ child.name }}</div>
            <div
              v-for="grandson in child.child"
              :key="grandson.code"
              class="form-container"
            >
            <div
              v-for="greatGS in grandson.child"
              :key="greatGS.code"
              class="form-container"
            >
            <div class="txt-name">
                {{ greatGS.name }}
                <t-popup :content="greatGS.ms"
                  ><icon style="cursor: pointer" name="info-circle"
                /></t-popup>
              </div>
             <div class="txt-label">评估得分</div>
              <t-radio-group v-model="greatGS.score" disabled>
                <t-radio value="1.0">100%</t-radio>
                <t-radio value="0.7">70%</t-radio>
                <t-radio value="0.5">50%</t-radio>
                <t-radio value="0.0">0%</t-radio>
              </t-radio-group>
              <div   v-if="greatGS.score != 0" class="txt-label">证据文件</div>
                <t-upload
                ref="uploadRef"
                disabled
                v-if="greatGS.score != 0"
                class="up-container"
                v-model="greatGS.optionsFileList"
                theme="file-flow"
                multiple
                name="files"
                :headers="{ authorization: token }"
                :action="url"
                placeholder="支持批量上传文件，文件格式不限，最多只能上传 5 份文件"
                :abridge-name="[6, 6]"
                :auto-upload="autoUpload"
                :max="5"
                :sizeLimit="{ size: 10, unit: 'MB', message: '文件大小不能超过10MB' }"
                @fail="handleFail"
                @remove="handleRemove"
                :onValidate="handleValidate"
              >
                <template  #fileListDisplay="{ files, dragEvents }">
                    <div class="custom-upload-display">
                      <div class="upload-table">
                        <div class="upload-table-header">
                          <div style="width: 34%">文件名</div>
                          <div style="width: 23%">大小</div>
                          <div style="width: 23%">状态</div>
                          <div style="width: 20%">操作</div>
                        </div>
                        <div class="upload-table-body">
                          <!-- {{files}} -->
                          <div v-for="(file, index) in files" :key="index" class="upload-table-row">
                            <div class="table-cell" style="width: 34%">
                              <span class="file-name table-txt">{{ file.name }}</span>
                            </div>
                            <div class=" table-txt" style="width: 23%">{{ formatFileSize(file.size) }}</div>
                            <div class=" table-txt txt-center" style="width: 23%">
                              <img class="table-success" src="@/assets/image/success.png" alt="">
                              <span class="table-txt" style="margin-left: 8px;">上传成功</span>
                            </div>
                            <div  style="width: 20%">
                              <!-- :disabled="getFileType(file.name) === 'unknown'" --> 
                                <t-button style=" padding: 0;" variant="text" size="small" theme="primary" @click="handlePreview(file)" :disabled="getFileType(file) === 'unknown'" >
                                预览
                              </t-button>

                               <t-button style="margin-left: 10px; padding: 0;" variant="text" size="small" theme="primary" @click="downloadFile(file.sjhgPath)">
                                下载
                              </t-button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                </template>
              </t-upload>
              <div class="txt-label">访谈结论</div>
              <t-textarea
                    v-model="greatGS.ftjl"
                    disabled
                    placeholder="请输入内容"
                    :autosize="{ minRows: 2}"
                  />
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>
  </t-form>

  <div class="t">
    <t-dialog class="preview-wrapper" overlay-class="custom-dialog-top" header="文件预览" placement="top" :visible="bodyVisible" :onClose="bodyClose" :onConfirm="bodyClose" 
  :footer="false" :dialogStyle="{
      width: '70vw',    // 支持百分比/vw单位
      maxWidth: 'none', // 禁用最大宽度限制
    }">
        <div slot="body">
          <div v-if="fileData">
            <!-- Word 预览 -->
            <div v-if="fileType === 'word'" class="docx-preview">
              <VueOfficeDocx
                :src="fileData"
                @rendered="handleRendered"
                @error="handleError"
              />
            </div>

            <!-- Excel 预览 -->
            <div v-if="fileType === 'excel'" class="excel-preview">
              <VueOfficeExcel
                :src="fileData"
                @rendered="handleRendered"
                @error="handleError"
              />
            </div>

            <!-- PDF 预览 -->
            <div v-if="fileType === 'pdf'" class="pdf-preview">
              <VuePdfEmbed
                :source="fileData"
                @rendered="handleRendered"
                @error="handleError"
              />
            </div>
          </div>
        </div>
  </t-dialog>
  </div>
  
 
  
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive } from "vue";
import { Icon } from "tdesign-icons-vue-next";
import { getAssessInterviewDetail } from "@/api/sjhg/assess";
import { MessagePlugin } from "tdesign-vue-next";
import { downloadFile2 } from '@/api/sjhg/upload'; 
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import VuePdfEmbed from 'vue-pdf-embed'
import '@vue-office/docx/lib/index.css'
import '@vue-office/excel/lib/index.css'

const props = defineProps({
  assessId: {
    type: String,
    default: "",
  }
});

//文件预览弹框
const bodyVisible = ref(false)

const bodyClose = () =>{
  bodyVisible.value = false
}

//----------------------------------------
// 响应式数据
const fileData = ref(null)
const fileType = ref('')
const loading = ref(false)
const error = ref('')

//评估详情
const assessInterviewDetail = reactive([]);

//--------------锚点----------------
const scrollContainer = ref(null);
let observer = null;
const defaultValue = ref(null); //默认选中menu
const formRef = ref(null);
const expandedKeys = ref([])

  // 菜单展开/收起回调
const handleExpand = (keys) => {
  console.log('当前展开的菜单:', keys);
  expandedKeys.value = keys;
};
const uploadRef = ref(null);

// 文件列表处理
const handleOptionFileList = (files) => {
  var newFiles = []
  files.forEach(item => {
    if (item.raw) {
      newFiles.push(...item.response.data)
    } else {
      newFiles.push(item)
    }
  });
  return newFiles
}

// 菜单点击处理
const handleMenuChange = (val) => {
  const target = document.getElementById(val);
  if (target) {
    target.scrollIntoView({ behavior: "smooth", block: "start" });
  }
};


//----------------------------锚点处理逻辑--------------------------------------
onBeforeUnmount(() => {
  if (observer) observer.disconnect();
});
onMounted(async() => {
  await getInterviewDetail();
  initIntersectionObserver();
});
const initIntersectionObserver = () => {
  const options = {
    root: scrollContainer.value, // 观察元素的根元素，null表示视窗
    threshold: 0.5, // 交叉比例的阈值，0.5表示元素一半进入视窗时触发回调
    rootMargin: "0px", // 根元素的边界
  };

  observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        //元素进入视框
        defaultValue.value = entry.target.id;
      }
    });
  }, options);

  assessInterviewDetail.forEach((item) => {
    item.child.forEach((child) => {
      const el = document.getElementById(child.code);
      if (el) observer.observe(el);
    });
  });
};

//-------------------------访谈评估接口--------------------------------------
const getInterviewDetail = () => {
  let params = {};
  params.assessId = props.assessId;
  getAssessInterviewDetail(params)
    .then((res) => {
      if (res.code == 200) {
        // reactive 赋值方式
        Object.assign(assessInterviewDetail, res.data);
        defaultValue.value = res.data[0].child[0].code;
        expandedKeys.value = assessInterviewDetail.map(item => item.id);
      }
    })
    .finally(() => {});
};

// ------------------- 下载 ---------------------
const downloadFile = async (objectPath) => {
  try {
    // const response = await axios.get('/sjhg/minio/download', {
    //   params: { bucketName: bucket, objectPath },
    //   responseType: 'blob'
    // });

    var params = {}
    params.objectPath = objectPath
    const response = await downloadFile2(params);

    // 生成临时下载链接
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', objectPath.split('/').pop() || 'file');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    console.error('下载失败:', error);
  }
};


//----------------------------文件预览------------------------------------
// 在 script setup 中添加以下方法
const formatFileSize = (size) => {
  if (!size) return '0 B';
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  return `${(size / (1024 * 1024)).toFixed(2)} MB`;
};

// function getFileType(filename) {
//   const extension = filename.split('.').pop().toLowerCase();
//   switch (extension) {
//     case 'doc':
//     case 'docx':
//       return 'word';
//     case 'xls':
//     case 'xlsx':
//       return 'excel';
//     case 'pdf':
//       return 'pdf';
//     case 'jpg':
//     case 'jpeg':
//     case 'png':
//       return 'image';
//     default:
//       return 'unknown';
//   }
// }

// 判断文件类型（扩展名 + MIME类型双校验）
const getFileType = (file) => {
  console.log('file---->',file)

  const extension = file.name.split('.').pop().toLowerCase()
  // const mime = file.type.toLowerCase()
  // , 'doc'
  if (['docx'].includes(extension) ) {
    return 'word'
  }
  // , 'xls', 'csv'
  // if (['xlsx'].includes(extension) ) {
  //   return 'excel'
  // }
  if (extension === 'pdf' ) {
    return 'pdf'
  }
  return 'unknown'
}
// 将文件读取为ArrayBuffer
const readFileAsBuffer = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = () => reject(new Error('文件读取失败'))
    reader.readAsArrayBuffer(file)
  })
}

// // 处理文件选择
// const handleFileChange = async (e) => {
//   const file = e.target.files[0]
//   console.log('--->',file)
//   if (!file) return

//   resetState()
//   loading.value = true

//   try {
//     // 1. 判断文件类型
//     fileType.value = getFileType(file)
//     if (!fileType.value) {
//       throw new Error('不支持的文件类型')
//     }

//     // 2. 读取文件为ArrayBuffer
//     fileData.value = await readFileAsBuffer(file)
//   } catch (err) {
//     error.value = err.message || '文件处理失败'
//   } finally {
//     loading.value = false
//   }
// }

// 渲染完成回调
const handleRendered = () => {
  console.log(`${fileType.value.toUpperCase()}渲染完成`)
}

// 错误处理
const handleError = (err) => {
  error.value = `预览失败: ${err.message || '未知错误'}`
}

// 重置状态
const resetState = () => {
  fileData.value = null
  fileType.value = ''
  error.value = ''
}

const handlePreview = async(file) => {

  bodyVisible.value = true

  console.log('--->',file)
  //---------------1 url图片预览---------------------------
  if (!file.url) return
  resetState()
  loading.value = true

  try {
    // 1. 通过fetch获取文件Blob
    const response = await fetch(file.url)
    if (!response.ok) throw new Error('文件下载失败')
    
    const blob = await response.blob()
    
    // 2. 判断文件类型
    // fileType.value = getFileTypeFromBlob(blob, file.url)
    // if (!fileType.value) throw new Error('不支持的文件类型')
    fileType.value = getFileType(file)
    if (!fileType.value) {
      throw new Error('不支持的文件类型')
    }

    // 3. 将Blob转为ArrayBuffer
    fileData.value = await blob.arrayBuffer()
  } catch (err) {
    error.value = err.message
  } finally {
    loading.value = false
  }


  //---------------2 本地图片预览-------------------------
  // if (!file) return

  // resetState()
  // loading.value = true

  // try {
  //   // 1. 判断文件类型
  //   fileType.value = getFileType(file)
  //   if (!fileType.value) {
  //     throw new Error('不支持的文件类型')
  //   }

  //   // 2. 读取文件为ArrayBuffer
  //   fileData.value = await readFileAsBuffer(file)
  // } catch (err) {
  //   error.value = err.message || '文件处理失败'
  // } finally {
  //   loading.value = false
  // }
  //-------------------3------------------------
  // // 实现预览逻辑
  // if (file.url) {
  //   // 如果是图片，可以使用图片预览组件
  //   if (file.type?.includes('image')) {
  //     // 使用 TDesign 的图片预览
  //     window.open(file.url, '_blank');
  //   } else {
  //     // 其他文件类型直接在新窗口打开
  //     window.open(file.url, '_blank');
  //   }
  // } else {
  //   MessagePlugin.warning('该文件暂不支持预览');
  // }
};

// 通过Blob和文件名判断类型
const getFileTypeFromBlob = (blob, filename) => {
  const extension = filename.split('.').pop().toLowerCase()
  const mime = blob.type.toLowerCase()

  if (['docx', 'doc'].includes(extension) || mime.includes('word')) {
    return 'word'
  }
  if (['xlsx', 'xls', 'csv'].includes(extension) || mime.includes('excel')) {
    return 'excel'
  }
  if (extension === 'pdf' || mime.includes('pdf')) {
    return 'pdf'
  }
  return ''
}
</script>

<style lang="scss" scoped>
// :deep(div.t-dialog ){
//   width: 80vw !important;
//   max-width: none !important;
// }

// :deep(.t-dialog){
//   padding-top: -100px !important;
// }

// :deep(.t-dialog--top) {
//     align-items: flex-start;
//     padding-top: 6vh !important;
// }
// :deep(.custom-dialog-top.t-dialog--top) {
//   top: 50px !important;
// }
:deep(.docx-wrapper){
  background: #fff !important;
}
:deep(.vue-office-docx .docx-wrapper){
  padding: 10px !important; 
}
:deep(.docx-wrapper>section.docx ){
  box-shadow: none !important;
}

// .file-preview-container {
//   max-width: 800px;
//   margin: 0 auto;
// }

// .file-input {
//   margin: 20px 0;
// }



.preview-wrapper {
  border: 1px solid #eee;
  min-width: 80vw;
  // min-height: 500px;
}

.status,
.error {
  padding: 10px;
  margin-top: 10px;
  text-align: center;
}

.error {
  color: red;
}

:deep(.t-upload__flow-placeholder ){
  font-family: PingFang SC-Bold, PingFang SC;
  font-weight: 400;
  color: #00000066 !important;
  font-size: 12px !important;
}
:deep(.t-upload__flow-empty ){
  font-family: PingFang SC-Bold, PingFang SC;
  font-weight: 400;
  color: #00000066 !important;
  font-size: 12px !important;
}
.form-container {
  :deep(.t-form__label) {
    color: #4e5969;
    font-size: 14px;
    font-weight: 400;
  }
}
.content-wrapper {
  flex: 1;
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.popup {
  padding: 6px;
}
// :deep(.t-upload__flow-empty) {
//   color: rgba(0, 0, 0, 0.4);
//   font-size: 14px;
// }
// :deep(.el-input__wrapper) {
//   background-color: #f2f3f5 !important;
//   box-shadow: none;
//   height: 32px;
// }
// :deep(.el-input__inner) {
//   min-width: 40vw;
//   height: 32px;
//   line-height: 32px;
//   color: #86909c;
// }
.up-container {
  margin-top: 8px;
  margin-bottom: 20px;
  :deep(.t-upload__flow-table > thead > tr > th){
    border: none;
  }
}
.title {
  color: #292b33;
  font-size: 18px;
  line-height: 24px;
  margin-top: 16px;
  letter-spacing: 0.5px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;
}
.sub-title {
  font-size: 16px;
  color: #565960;
  position: relative;
  padding-left: 8px;
  margin-top: 24px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;

  &::before {
    content: ""; /* 在内容前添加竖线 */
    position: absolute;
    width: 3px;
    height: 18px;
    border-radius: 3px;
    background-color: #1966ff;
    left: 0;
    top: 2px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
  }
}
.txt-name {
  color: #565960;
  font-size: 14px;
  line-height: 22px;
  margin-top: 16px;
  font-weight: 500;
  font-family: PingFang SC-Bold, PingFang SC;
}
.txt-label {
  color: #4e5969;
  font-size: 14px;
  font-weight: 400;
  line-height: 22px;
  margin-top: 8px;
  margin-bottom: 4px;
  font-family: PingFang SC-Bold, PingFang SC;
}
.upload-con1 {
  margin-bottom: 0px;
  height: calc(100vh - 230px);
}
.upload-con2 {
  margin-bottom: 0px;
  height: calc(100vh - 230px);
}
.upload-container {
  position: relative;
  display: flex;
  &__menu {
    position: sticky;
    top: 0;
    margin-top: -16px;

    :deep(.t-menu__content) {
      font-family: PingFang SC-Bold, PingFang SC;
      font-size: 14px;
      font-weight: 400;
      span{
        font-weight: 600;
        color: #292B33;
      }
    }
    :deep(.t-default-menu__inner .t-menu) {
      padding: 0;
      margin-top: 8px;
    }
    :deep(.t-default-menu .t-menu__item.t-is-active:not(.t-is-opened)) {
      color: #1966ff;
    }
    :deep(.t-divider--vertical) {
      margin: 0;
    }
    :deep(.t-default-menu__inner .t-menu--scroll) {
      overflow-y: auto;
      -ms-overflow-style: none;
      scrollbar-width: none;
    }
  }
  &__line {
    height: calc(100% + 20px);
    width: 2px;
    margin-top: -16px;
  }
  &__up {
    margin: 0 16px;
    flex-grow: 1; /* 让内容区域填充剩余空间 */
    overflow-y: auto; /* 内容区域允许垂直滚动 */
    margin-top: -16px;

    :deep(.t-is-error .t-input__extra) {
      z-index: 99;
    }
    :depp(.t-upload__tips) {
      display: inline;
    }
  }
  &__up::-webkit-scrollbar {
    display: none;
  }

  //隐藏滚动条
  &__up {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  &__menu::-webkit-scrollbar {
    display: none;
  }
  &__menu {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
}

// .custom-upload-display {
//   margin-top: 16px;
//   max-width: 45vw;
// }

// .upload-table {
//   width: 100%;
//   // border: 1px solid #e7e7e7;
//   border-radius: 4px;
//   overflow: hidden;
// }

// .upload-table-header {
//   display: flex;
//   // background-color: #f5f5f5;
//   height: 46px;
//   padding: 0 16px;
//   line-height: 46px;
//   color: #00000066;
//   font-size: 14px;
//   // border-bottom: 1px solid #e7e7e7;
// }

// // .header-cell {
//   // padding: 0 8px;
// // }

// .upload-table-body {
//   background-color: #fff;
//   border: 1px dashed #e7e7e7;
// }

// .upload-table-row {
//   display: flex;
//    height: 46px;
//   line-height: 46px;
//     padding: 0 16px;
//   align-items: center;
//   border-bottom: 1px solid #f0f0f0;
// }

// .upload-table-row:last-child {
//   border-bottom: none;
// }

// .table-cell {
//   display: flex;
//   align-items: center;
// }
// .table-txt {
//   color: #000000E5;
//   font-size: 14px;
// }
// .table-success {
//   width: 16px;
//   height: 16px;
// }
// .txt-center{
//   display: flex;
//   align-items: center;
// }

// .file-name {
//   overflow: hidden;
//   text-overflow: ellipsis;
//   white-space: nowrap;
// }
.t-button {
  height: auto;
}
</style>
